package com.airy.apprepairequipment.socket;

import java.net.Socket;

/**
 * @description: 客户端工作线程
 * @author airy
 * @date 2020/11/19 8:37
 */

/**
 * 二：客户端Socket线程实例，通过Socket的getOutputStream().write(message.getBytes())方法传入message消息
 */
public class SocketClientWorker implements Runnable {

    //通信socket
    private Socket clientSocket;
    //客户端名称
    private String clientName;
    //发送消息间隔
    private long sleepTime;
    //发送的消息内容
    //private String message;

    public SocketClientWorker(String host, int port, String clientName, long sleepTime) {
        try {
            clientSocket = new Socket(host, port);
            this.clientSocket = clientSocket;
            this.clientName = clientName;
            this.sleepTime = sleepTime;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        {
            while (true) {
                try {
                    clientSocket.getOutputStream().write(clientName.getBytes());
                    System.out.println(clientName + "客户端向服务器发送消息: " + clientName);
                    Thread.sleep(sleepTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
